/**
 * 
 */
package tk.sunlatus.project.config.xml;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import tk.sunlatus.project.config.domain.ConfigFile;


/**
 * @author sunlotus
 * 
 */
public class ConfigParserDom4jImpl {

    private static final Logger LOGGER = Logger.getLogger(ConfigParserDom4jImpl.class);

    
    private List<ConfigFile> configFileList = null;

    public void parseDom(File inputXml) {
        SAXReader saxReader = new SAXReader();
        Document document;
        try {
            document = saxReader.read(inputXml);
            Element employees = document.getRootElement();
            for (Iterator<?> i = employees.elementIterator(); i.hasNext();) {
                Element employee = (Element) i.next();
                configFileList = new ArrayList<ConfigFile>();
                for (Iterator<?> j = employee.elementIterator(); j.hasNext();) {
                    parseNode((Element) j.next());
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    private void parseNode(Element node) {
        if (node.getName().equals("config_file")) {
            ConfigFile file = new ConfigFile();
            configFileList.add(file);
            parseConfigfile(node, file);
        } else {
            // TODO 记录日志：暂不支持解析该标签
            LOGGER.debug("unSupport label, label=<" + node.getName() + ">");
        }
    }

    private void parseConfigfile(Element configFile, ConfigFile file) {
        for (Iterator<?> j = configFile.elementIterator(); j.hasNext();) {
            Element node = (Element) j.next();
            fillConfigFile(node.getName(), node.getText(), file);
        }
        LOGGER.debug("parse ConfigFile success, file=" + file);
    }

    private void fillConfigFile(String name, String text, ConfigFile file) {
        if ("key".equals(name)) {
            file.setKey(text);
        } else if ("type".equals(name)) {
            file.setType(text);
        } else if ("path".equals(name)) {
            file.setPath(text);
        } else if ("loadType".equals(name)) {
            file.setRefresh(text);
        } else {
            // TODO 错误日志：无法识别的标签
            LOGGER.debug("Error:error label:<" + name + ">, value=" + text);
            return;
        }
        // TODO 操作成功日志，记录操作结果
    }

    public List<ConfigFile> getConfigFileList() {
        return configFileList;
    }
}
